﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Miao.UI
{
    /// <summary>
    /// 读条Panel，CloseButton可以理解为读条结束后关闭
    /// </summary>
    public abstract class UISceneLoadingPanel : UIMotionPanel
    {
        protected AsyncOperation sceneAsync;
        string sceneName;
        int sceneId = -1;
        bool ClickClose;
        public void SetChangeScene(string sceneName, bool ClickClose)
        {
            this.sceneName = sceneName;
            this.ClickClose = ClickClose;
        }
        public void SetChangeScene(int sceneId, bool ClickClose)
        {
            this.sceneId = sceneId;
            this.ClickClose = ClickClose;

        }

        protected void Update()
        {
            if (sceneAsync != null)
            {
                LoadingUpdate();
            }
        }
        virtual protected void LoadingUpdate() { }


        public override async Task OnCreate()
        {
            ShowMotion = LoadStart();
            HideMotion = LoadComplete();
            await base.OnCreate();
        }
        public abstract IMotion LoadStart();
        public abstract IMotion LoadComplete();
        public override void OnShow()
        {
            base.OnShow();
            if (string.IsNullOrEmpty(sceneName))
            {
                sceneAsync = SceneManager.LoadSceneAsync(sceneId);
            }
            else
            {
                sceneAsync = SceneManager.LoadSceneAsync(sceneName);
            }
            if (ClickClose)
            {
                sceneAsync.completed += this.LoadCompleted;
            }
            else
            {
                sceneAsync.completed += Close;
            }
        }

        virtual protected void LoadCompleted(AsyncOperation obj)
        {
            closeButton.onClick.AddListener(Close);
        }

        private void Close(AsyncOperation obj)
        {
            UIManager.SetCameraStack();
            Close();
        }
    }
}

